import { Component, Injector, ViewChild } from '@angular/core';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import {
    InspectionCheckServiceProxy, InspectionSeverityDescOutDto, OperationHistoryServiceProxy,
    InspectionStartServiceProxy, CommonServiceProxy, QualityPlatformServiceProxy, ProductionDesignServiceProxy
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as moment from 'moment';


@Component({
    selector: 'app-view-exceptions',
    templateUrl: './view-exceptions.component.html',
    styleUrls: ['./view-exceptions.component.less']
})
export class ViewExceptionsComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;



    constructor(
        injector: Injector,
        private _inspectionCheckServiceProxy: InspectionCheckServiceProxy,
        private _operationHistoryServiceProxy: OperationHistoryServiceProxy,
        private _inspectionStartServiceProxy: InspectionStartServiceProxy,
        private _commonServiceProxy: CommonServiceProxy,
        private _qualityPlatformServiceProxy: QualityPlatformServiceProxy,
        private _productionDesignServiceProxy: ProductionDesignServiceProxy,

    ) {
        super(injector);
    }




    resumeVisible: boolean = false;//异常履历
    rangeDates: string = "";
    activeIndex: number = 0;//履历步骤条选中index
    sureVisible: boolean = false;//确认结果
    images = [];
    queryInfoLeft = {
        model: undefined,
        lotNo: undefined,
    };//查询条件
    modelList = [];
    lotNoList = [];
    files2 = [];
    queryInfo = {
        startDateTime: undefined,
        endDateTime: undefined
    };//查询条件
    typeDescList: any[];//一级异常下拉
    itemInfoList: any[];//二级异常下拉
    severityDescList: InspectionSeverityDescOutDto[];//等级下拉
    userList: any[];//处理人 提报人下拉
    uploadedFiles: any[] = [];

    addInfoUi: any = {
        inspectionTypeDescId: { id: undefined },//一级异常id
        inspectionItemInfoId: { id: undefined },//二级异常id
        inspectionSeverityDescId: { id: undefined },//异常等级id
        handlerId: { id: undefined },//处理人id
        inspectionDetails: "",//异常描述
        codeFormatId: { id: undefined },//编码规则id
        inspectionFileUploadDto: []

    };//新增集合

    savingsetDia: boolean = false;//禁止频繁保存操作

    logList: any[];//异常履历 列表

    checkTitle: any;//异常数量统计
    distribution: any;//未关闭异常分布
    creationTime = undefined;
    selectedFiles1 = undefined;
    ngOnInit() {
        this.getmodelList()
    }
    //型号下拉
    getmodelList() {
        this._qualityPlatformServiceProxy.getModelNameList(undefined)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.modelList.push(data);
                }
            });
    }
    getLotNoList(event): any {
        this._qualityPlatformServiceProxy.getLotNoList(undefined, this.queryInfoLeft.model)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.lotNoList.push(data);
                }
            });
    }
    // 重置
    reset() {
        this.queryInfo = {
            startDateTime: "",
            endDateTime: ""
        };//查询条件
    }
    nodeSelect(event) {
        if (event.node.isRelation === 1) {//树结构判断是否有子节点
            event.node.children = []
            event.node.treeList = []
            this.getProductionTechquine(event.node.id, event.node)
        }
        this.getDescList();

    }
    // 加载工序工步节点 
    getProductionTechquine(nodeId, node) {
        this._qualityPlatformServiceProxy.getQualityWorkStepList(
            nodeId
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                let childNodes = this.isEqual(JSON.parse(JSON.stringify(result)))
                node.children = childNodes
                node.treeList = childNodes
            });
    }
    getDesigenTree() {
        this._qualityPlatformServiceProxy.getTreeContainRoot(
            this.queryInfoLeft.lotNo ? this.queryInfoLeft.lotNo : undefined,
            this.queryInfoLeft.model ? this.queryInfoLeft.model : undefined,
        )
            .pipe(finalize(() => { })).subscribe(result => {
                this.files2 = [];
                this.files2.push({
                    ...result.parentNode,
                    key: -1,
                    nodeDrawingNo: result.parentNode.drawingNo,
                    nodeName: result.parentNode.modelName,
                    model: result.parentNode.model,
                    lotNo: result.parentNode.lotNo,
                    stageSign: result.parentNode.stageSign,
                    children: result.childNodes
                })
                this.expandAllTree();
            })
    }
    // 组合树结构数据
    isEqual(obj1) {
        for (const iterator of obj1) {
            iterator.label = iterator.nodeName
            if (iterator.treeList) {
                iterator.children = iterator.treeList
                this.isEqual(iterator.treeList)
            }
        }
        return obj1
    }
    expandAllTree() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }
    private expandRecursive(node: any, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    //异常列表
    getDescList(event?: LazyLoadEvent): void {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
      
        let descId = undefined;//根节点
        let nodeId = undefined;//不是工序工步又不是根节点
        let processId = undefined;//工序
        this.queryInfo.startDateTime = this.rangeDates[0]
        this.queryInfo.endDateTime = this.rangeDates[1]
        if (this.selectedFiles1.key) {
            descId = this.selectedFiles1.id;
        }else if (this.selectedFiles1.nodeLevel != 8 && this.selectedFiles1.nodeLevel != 9) {
            nodeId = this.selectedFiles1.id;
        }
        if (this.selectedFiles1.nodeLevel == 8 || this.selectedFiles1.nodeLevel == 9) {
            processId = this.selectedFiles1.id
        }
        this._inspectionCheckServiceProxy.getInspectionStandardDescList(
            descId,
            nodeId,
            processId,
            this.queryInfo.startDateTime,
            this.queryInfo.endDateTime,
            this.primengTableHelper.getSorting(this.dataTable),//undefined
            this.primengTableHelper.getMaxResultCount(this.paginator, event),//10
            this.primengTableHelper.getSkipCount(this.paginator, event)//0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
                this.getCheckTitle()
            });
    }
    //异常数量统计接口
    getCheckTitle(): void {
        let descId = undefined;//根节点
        let nodeId = undefined;//不是工序工步又不是根节点
        let processId = undefined;//工序
        if (this.selectedFiles1.key) {
            descId = this.selectedFiles1.id;
        }else if (this.selectedFiles1.nodeLevel != 8 && this.selectedFiles1.nodeLevel != 9) {
            nodeId = this.selectedFiles1.id;
        }
        if (this.selectedFiles1.nodeLevel == 8 || this.selectedFiles1.nodeLevel == 9) {
            processId = this.selectedFiles1.id
        }
        this._inspectionCheckServiceProxy.getInepectionCheckTitle(
            descId,
            nodeId,
            processId,
            this.queryInfo.startDateTime,
            this.queryInfo.endDateTime,
            undefined,
            10,
            0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.checkTitle = result
            });
    }
    // 异常履历
    getOperationLogList(id): void {
        this.resumeVisible = true
        this._operationHistoryServiceProxy.getOperationLogList(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.logList = result
            });
    }
    // 查看异常
    seeDetail(item): void {
        this.sureVisible = true
        this.addInfoUi = item
        //一级异常 回显
        console.log(this.typeDescList);
        
        // this.addInfoUi.inspectionTypeDescId = this.typeDescList.filter((ele, index) => {
        //     return ele.id === item.inspectionTypeDescId
        // })[0]
        //二级异常 回显
        // this.addInfoUi.inspectionItemInfoId = this.itemInfoList.filter((ele, index) => {
        //     return ele.id === item.inspectionItemInfoId
        // })[0]
        //异常等级 回显
        // this.addInfoUi.inspectionSeverityDescId = this.severityDescList.filter((ele, index) => {
        //     return ele.id === item.inspectionSeverityDescId
        // })[0]
        //处理人 回显
        // this.addInfoUi.handlerId = this.userList.filter((ele, index) => {
        //     return ele.id === item.handlerId
        // })[0]
        this.images = [];

        let imgArr = []

        item.inspectionFileUploadDto.forEach(element => {

            let obj = {
                name: element.fileName,
                size: element.size,
                objectURL: element.fileUrl,
                id: element.id,
            }

            imgArr.push(obj)
        });
        this.uploadedFiles = imgArr


        this.addInfoUi.inspectionFileUploadDto = item.inspectionFileUploadDto
        this.addInfoUi.creationTime = moment(this.addInfoUi.creationTime).format('YYYY-MM-DD HH:mm:ss');
        this.addInfoUi.completeTime = moment(this.addInfoUi.completeTime).format('YYYY-MM-DD HH:mm:ss');

    }
    onHideSureVisible() {
        this.creationTime = undefined;
    }
}
